package com.smartcruise.task;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.dialog.widget.NormalListDialog;
import com.smartcruise.R;
import com.smartcruise.base.BaseActivity;
import com.smartcruise.data.cruiseData.CoordinateBean;
import com.smartcruise.data.cruiseData.CruiseContract;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.data.cruiseData.MapElementEntityListBean;
import com.smartcruise.data.cruiseData.NodeTaskListBean;
import com.smartcruise.main.mainFragment.tools.map.NavigateActivity;
import com.smartcruise.service.LocationManager;
import com.smartcruise.task.nodeTaskDataEdit.NodeTaskDataEditActivity;
import com.smartcruise.util.IntentUtils;
import com.smartcruise.util.Key;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.TimeUtils;
import com.smartcruise.util.network.netUtils.NetCollection;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.realm.ObjectChangeSet;
import io.realm.RealmChangeListener;
import io.realm.RealmList;
import io.realm.RealmModel;
import io.realm.RealmObjectChangeListener;

/**
 * Created by FengChaoQun
 * on 2018/1/25 0025
 * 任务详情(带地图)
 */

public class TaskWithMapActivity extends BaseActivity implements TaskWithMapContract.View, AMap.OnMyLocationChangeListener {

    @BindView(R.id.leftArrow)
    ImageView leftArrow;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightText)
    TextView rightText;
    @BindView(R.id.statusText)
    TextView statusText;
    @BindView(R.id.taskTitle)
    TextView taskTitle;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.deviate)
    TextView deviate;
    @BindView(R.id.taskViewLay)
    LinearLayout taskViewLay;
    @BindView(R.id.sos)
    TextView sos;
    @BindView(R.id.report)
    TextView report;
    @BindView(R.id.navigation)
    TextView navigation;
    @BindView(R.id.bottomButton)
    Button bottomButton;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.bottomMenuLay)
    LinearLayout bottomMenuLay;
    @BindView(R.id.evaluation)
    TextView evaluation;
    @BindView(R.id.statusLay)
    LinearLayout statusLay;

    private AMap aMap;
    private MyLocationStyle myLocationStyle;

    private CruiseData cruiseData;
    private RealmList<NodeTaskListBean> nodeTaskList;
    private TaskWithMapContract.Presenter mPresenter;
    private HashMap<NodeTaskListBean, Marker> markerMap = new HashMap<>();
    private boolean isStarted;
    private Disposable calculateDistanceDisposable;
    private List<CoordinateBean> copyCoordinateList;//复制出来的路径

    /**
     * description:打开该界面  查看一个当天的任务
     */

    public static void start(Context context, String taskId) {
        Intent intent = new Intent(context, TaskWithMapActivity.class);
        intent.putExtra(IntentUtils.DATA, taskId);
        context.startActivity(intent);
    }

    /**
     * description:打开该界面 查看一个指定日期的任务
     */

    public static void start(Context context, String taskId, Calendar calendar) {
        Intent intent = new Intent(context, TaskWithMapActivity.class);
        intent.putExtra(IntentUtils.DATA, taskId);
        intent.putExtra(IntentUtils.DATE, calendar);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_with_map);
        ButterKnife.bind(this);
        setEnableRightSlide(false);
        mapView.onCreate(savedInstanceState);

        String id = getIntent().getStringExtra(IntentUtils.DATA);
        Calendar calendar = (Calendar) getIntent().getSerializableExtra(IntentUtils.DATE);
        if (TextUtils.isEmpty(id)) {
            showToast(getString(R.string.needId));
            finish();
            return;
        }
        cruiseData = realm.where(CruiseData.class).equalTo(Key.id, id).findFirst();
        if (cruiseData == null) {
            showToast(getString(R.string.noContent));
            finish();
            return;
        }

        mPresenter = new TaskWithMapPresenterImp(this, cruiseData, calendar);

        cruiseData.addChangeListener(new RealmObjectChangeListener<RealmModel>() {
            @Override
            public void onChange(RealmModel realmModel, ObjectChangeSet changeSet) {
                if (changeSet.isDeleted()) {
                    showToast("任务不存在或已经删除");
                    finish();
                } else {
                    initView();
                }
            }
        });

        initView();
    }

    private void initView() {
        isStarted = CruiseContract.isStarted(cruiseData);
        nodeTaskList = cruiseData.getNodeTaskList();
        if (ListUtils.isHaveContent(nodeTaskList)) {
            nodeTaskList.addChangeListener(new RealmChangeListener<RealmList<NodeTaskListBean>>() {
                @Override
                public void onChange(RealmList<NodeTaskListBean> nodeTaskListBeans) {
                    if (cruiseData.isValid()) {//防止任务被删除
                        initNode();
                    }
                }
            });
        }
        title.setText(cruiseData.getType());
        taskTitle.setText(cruiseData.getName());
        deviate.setText(cruiseData.getThreshold() + "米");
        String realCostTime = cruiseData.getRealCostTime();
        if (TextUtils.isEmpty(realCostTime)) {
            time.setText(cruiseData.getCostTime() + "小时");
        } else {
            time.setText(realCostTime + "/" + cruiseData.getCostTime() + "小时");
        }

        if (!cruiseData.isCopyData() && !cruiseData.isFromNet()) {//原任务
            buildNewTask();
        } else if (cruiseData.isCopyData()) {//本地任务
            buildLocalTask();
        } else if (cruiseData.isFromNet()) {
            if (cruiseData.getAuditStatus() == CruiseContract.AUDITED) {
                if (cruiseData.isAuditSuccess()) {
                    buildSuccessTask();
                } else {
                    buildFailTask();
                }
            } else {
                buildFromNetTask();
            }
        }

        if (aMap == null) {
            aMap = mapView.getMap();
            initMap();
        }

    }

    /**
     * description:初始化本地任务的布局
     */

    private void buildLocalTask() {
        switch (cruiseData.getStatusInApp()) {
            case CruiseContract.TASK_IS_WAIT_START:
                buildNewTask();
                break;
            case CruiseContract.TASK_IS_RUNNING:
                buildRunningTask();
                break;
            case CruiseContract.TASK_IS_PAUSE:
                buildPauseTask();
                break;
            case CruiseContract.TASK_IS_END:
                buildEndedTask();
                break;
        }
    }

    /**
     * description:构建新任务的布局
     */

    private void buildNewTask() {
        statusLay.setVisibility(View.GONE);
        bottomMenuLay.setVisibility(View.GONE);
        bottomButton.setText(R.string.startTask);
    }

    /**
     * description:构建正在运行的任务布局
     */

    private void buildRunningTask() {
        statusLay.setVisibility(View.GONE);
        bottomMenuLay.setVisibility(View.VISIBLE);
        bottomButton.setVisibility(View.GONE);
    }

    /**
     * description:构建暂停中的任务的布局
     */

    private void buildPauseTask() {
        statusLay.setVisibility(View.VISIBLE);
        statusText.setText(R.string.paused);
        evaluation.setVisibility(View.GONE);
        bottomMenuLay.setVisibility(View.VISIBLE);
        bottomButton.setVisibility(View.VISIBLE);
        bottomButton.setText("继续进行任务");
    }

    /**
     * description:构建已经结束的任务的布局
     */

    private void buildEndedTask() {
        statusLay.setVisibility(View.GONE);
        bottomMenuLay.setVisibility(View.GONE);
        bottomButton.setVisibility(View.VISIBLE);
        bottomButton.setText("上传全部节点任务");
    }

    /**
     * description:构建从服务器下载下来的已经上传了的但是还未审核的任务的布局
     */

    private void buildFromNetTask() {
        statusLay.setVisibility(View.GONE);
        bottomMenuLay.setVisibility(View.GONE);
        bottomButton.setVisibility(View.GONE);
    }

    /**
     * description:构建审核通过的任务的布局
     */

    private void buildSuccessTask() {
        statusLay.setVisibility(View.VISIBLE);
        statusLay.setBackgroundColor(getResources().getColor(R.color.titleColorAlpha0_5));
        statusText.setText("任务完成");
        evaluation.setVisibility(View.VISIBLE);
        evaluation.setText("评价:" + cruiseData.getEvaluation());
        bottomMenuLay.setVisibility(View.GONE);
        bottomButton.setVisibility(View.GONE);
    }

    /**
     * description:构建审核失败的任务的布局
     */

    private void buildFailTask() {
        statusLay.setVisibility(View.VISIBLE);
        statusLay.setBackgroundColor(getResources().getColor(R.color.sosOrange));
        statusText.setText("被驳回");
        evaluation.setVisibility(View.VISIBLE);
        evaluation.setText(cruiseData.getEvaluation());
        bottomMenuLay.setVisibility(View.GONE);
        bottomButton.setVisibility(View.GONE);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        if (cruiseData != null) {
            cruiseData.removeAllChangeListeners();
        }
        if (nodeTaskList != null) {
            nodeTaskList.removeAllChangeListeners();
        }
        if (calculateDistanceDisposable != null) {
            calculateDistanceDisposable.dispose();
        }
        super.onDestroy();
        mapView.onDestroy();
    }

    @OnClick(R.id.leftArrow)
    public void onLeftArrowClicked() {
        finish();
    }

    @OnClick(R.id.rightText)
    public void onRightTextClicked() {
        mPresenter.clickOnRightText();
    }

    @OnClick(R.id.taskViewLay)
    public void onTaskViewLayClicked() {
        mPresenter.clickOnTaskOverview();
    }

    @OnClick(R.id.sos)
    public void onSosClicked() {
        mPresenter.clickOnSOS();
    }

    @OnClick(R.id.report)
    public void onReportClicked() {
        mPresenter.clickOnReport();
    }

    @OnClick(R.id.navigation)
    public void onNavigationClicked() {
        mPresenter.clickOnNavigation();
    }

    @OnClick(R.id.bottomButton)
    public void onBottomButtonClicked() {
        mPresenter.clickOnBottomButton();
    }

    private void initMap() {
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setCompassEnabled(true);//设置指南针可见
        aMap.getUiSettings().setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        aMap.setMyLocationStyle(myLocationStyle);

        aMap.setOnMyLocationChangeListener(this);

        //移动到对应的位置
        if (cruiseData.getPatrollingMapEntity() != null) {
            LatLngBounds latLngBounds = cruiseData.getPatrollingMapEntity().getLatBounds();
            if (latLngBounds != null) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 25));
            }
        }

        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                clickOnNode(marker);
                return false;
            }
        });

        //添加节点任务
        initNode();

        //添加巡航路线
        buildPath();

        //添加地图标记物
        buildMark();

    }

    private void initNode() {
        isStarted = CruiseContract.isStarted(cruiseData);
        //清空已有的节点标记
        for (Map.Entry<NodeTaskListBean, Marker> nodeTaskListBeanMarkerEntry : markerMap.entrySet()) {
            nodeTaskListBeanMarkerEntry.getValue().remove();
        }
        markerMap.clear();

        if (ListUtils.isHaveContent(nodeTaskList)) {
            for (NodeTaskListBean nodeTaskListBean : nodeTaskList) {
                if (isStarted && !cruiseData.isFromNet() && CruiseContract.isOnPosition(lastLocation, cruiseData, nodeTaskListBean)) {
                    addNode(nodeTaskListBean, true);
                } else {
                    addNode(nodeTaskListBean, false);
                }
            }
        }
    }

    private void clickOnNode(final Marker marker) {
        if (!isStarted) { //如果是新任务 尚未开始 则提醒用户先开始任务
            showToast("请先开启任务");
            title.post(new Runnable() {
                @Override
                public void run() {//隐藏气泡
                    marker.hideInfoWindow();
                }
            });
            return;
        }

        NodeTaskListBean nodeTaskListBean = null;
        for (Map.Entry<NodeTaskListBean, Marker> nodeTaskListBeanStringEntry : markerMap.entrySet()) {
            if (marker.equals(nodeTaskListBeanStringEntry.getValue())) {
                nodeTaskListBean = nodeTaskListBeanStringEntry.getKey();
                break;
            }
        }

        if (nodeTaskListBean != null) {
            if (cruiseData.isFromNet()) {//如果任务来自于服务器 则直接打开
                NodeTaskDataEditActivity.start(getActivity(), cruiseData.getId(), nodeTaskListBean.getNodeId());
                return;
            }
            final NormalDialog nodeInfoDialog = new NormalDialog(getActivity());
            String lat = nodeTaskListBean.getPatrollingNodeEntity().getCoordinateList().get(0).getLat().substring(0, 8);
            String lng = nodeTaskListBean.getPatrollingNodeEntity().getCoordinateList().get(0).getLng().substring(0, 8);
            final CoordinateBean coordinateBean = nodeTaskListBean.getPatrollingNodeEntity().getCoordinateList().get(0);
            final NodeTaskListBean finalNodeTaskListBean = nodeTaskListBean;
            nodeInfoDialog.title("节点信息")
                    .content("节点名称:" + nodeTaskListBean.getPatrollingNodeEntity().getName() + "\n"
                            + "节点坐标:" + lat + ":" + lng)
                    .btnText("导航", "编辑")
                    .setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            NavigateActivity.start(getActivity(), new LatLng(coordinateBean.getLatDouble(), coordinateBean.getLngDouble()), null);
                            nodeInfoDialog.dismiss();
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            gotoEditNodeData(finalNodeTaskListBean, marker);
                            nodeInfoDialog.dismiss();
                        }
                    });
            nodeInfoDialog.show();
        } else {
            showToast("没有找到该节点");
        }
    }

    private void gotoEditNodeData(NodeTaskListBean nodeTaskListBean, final Marker marker) {
        if (CruiseContract.isOnPosition(lastLocation, cruiseData, nodeTaskListBean)) {
            NodeTaskDataEditActivity.start(getActivity(), cruiseData.getId(), nodeTaskListBean.getNodeId());
        } else {
//                showToast("当前不在指定位置范围内，请接近指定地点");
            final CoordinateBean coordinateBean = nodeTaskListBean.getPatrollingNodeEntity().getCoordinateList().get(0);
            if (lastLocation == null) {
                showToast("错误：没有找到该节点坐标，请联系管理员");
                return;
            }

            double distance = LocationManager.getDistance(lastLocation.getLatitude(), lastLocation.getLongitude(), coordinateBean.getLatDouble(), coordinateBean.getLngDouble());
            showToast("当前距离任务节点:" + distance + "--" + "允许偏移量:" + cruiseData.getThreshold());

            title.post(new Runnable() {
                @Override
                public void run() {//隐藏气泡
                    marker.hideInfoWindow();
                }
            });

            final NormalDialog dialog = new NormalDialog(getActivity());
            dialog.content("当前不在指定位置范围内，请接近指定地点")
                    .btnText("导航", "取消")
                    .setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            NavigateActivity.start(getActivity(), new LatLng(coordinateBean.getLatDouble(), coordinateBean.getLngDouble()), null);
                            dialog.dismiss();
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                        }
                    });
            dialog.show();
        }
    }

    private void addNode(NodeTaskListBean nodeTaskListBean, boolean showInfoWindow) {
        CoordinateBean coordinateBean = nodeTaskListBean.getPatrollingNodeEntity().getCoordinateList().get(0);
        MarkerOptions options = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(nodeTaskListBean.checkContent(cruiseData) ? BitmapDescriptorFactory.HUE_GREEN : BitmapDescriptorFactory.HUE_ORANGE))
                .position(new LatLng(coordinateBean.getLatDouble(), coordinateBean.getLngDouble()))
                .snippet(nodeTaskListBean.getPatrollingNodeEntity().getName())
                .title("点击完成任务")
                .infoWindowEnable(isStarted && !cruiseData.isFromNet())
                .draggable(false);
        Marker marker = aMap.addMarker(options);
        if (showInfoWindow) {
            marker.showInfoWindow();
        } else {
            marker.hideInfoWindow();
        }
        markerMap.put(nodeTaskListBean, marker);
    }

    private void buildPath() {
        if (cruiseData.getPatrollingRouteEntity() != null && cruiseData.getPatrollingRouteEntity().getCoordinateList() != null &&
                !cruiseData.getPatrollingRouteEntity().getCoordinateList().isEmpty()) {
            //将路径上的坐标全部复制出来
            copyCoordinateList = realm.copyFromRealm(cruiseData.getPatrollingRouteEntity().getCoordinateList());

            List<LatLng> latLngs = new ArrayList<>();
            for (CoordinateBean coordinateBean : cruiseData.getPatrollingRouteEntity().getCoordinateList()) {
                latLngs.add(coordinateBean.getLatLng());
            }
            PolylineOptions polylineOptions = new PolylineOptions();
            polylineOptions.addAll(latLngs).width(5).color(getResources().getColor(R.color.titleColor));
            aMap.addPolyline(polylineOptions);
        }
    }

    private void buildMark() {
        RealmList<MapElementEntityListBean> mapElementEntityList = cruiseData.getMapElementEntityList();
        if (ListUtils.isHaveContent(mapElementEntityList)) {
            for (MapElementEntityListBean mapElementEntityListBean : mapElementEntityList) {
                RealmList<CoordinateBean> coordinateList = mapElementEntityListBean.getCoordinateList();
                if (ListUtils.isHaveContent(coordinateList)) {
                    List<LatLng> latLngs = new ArrayList<>();
                    for (CoordinateBean coordinateBean : coordinateList) {
                        latLngs.add(coordinateBean.getLatLng());
                    }
                    PolylineOptions polylineOptions = new PolylineOptions();
                    polylineOptions.addAll(latLngs).width(5).color(getResources().getColor(R.color.green2));
                    aMap.addPolyline(polylineOptions);
                }
            }
        }
    }

    private Location lastLocation;//最近一次位置

    //2s回调一次位置
    @Override
    public void onMyLocationChange(Location location) {
        //如果任务尚未开始 或者任务已经上传到服务器 或者坐标为空 则不需要监听当前位置
        if (!isStarted || cruiseData.isFromNet() || location == null) {
            return;
        }

        //偶尔会出现收到坐标为0.0的情况 在这里过滤掉这种数据
        if (location.getLatitude() == 0 && location.getLongitude() == 0) {
            return;
        }

        //上传当前位置  如果是第一次上传或者和上一次上传的坐标距离大于20 则需要上传 否则 不用上传
        if (lastLocation == null || LocationManager.getDistance(lastLocation.getLatitude(), lastLocation.getLongitude(),
                location.getLatitude(), location.getLongitude()) > LocationManager.minDistance) {
            NetCollection.pushLocation(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
            lastLocation = location;
        }

        if (nodeTaskList != null) {
            for (NodeTaskListBean nodeTaskListBean : nodeTaskList) {
                Marker marker = markerMap.get(nodeTaskListBean);
                if (isStarted && !cruiseData.isFromNet() && CruiseContract.isOnPosition(new LatLng(location.getLatitude(), location.getLongitude()), cruiseData, nodeTaskListBean)) {
                    marker.showInfoWindow();
                } else {
                    marker.hideInfoWindow();
                }
            }
        }

        //只有任务在进行或暂停的时候 才监测当前是否偏移路线
        if (!cruiseData.isFromNet() && (CruiseContract.TASK_IS_RUNNING.equals(cruiseData.getStatusInApp())
                || CruiseContract.TASK_IS_PAUSE.equals(cruiseData.getStatusInApp()))) {
            if (ListUtils.isHaveContent(copyCoordinateList)) {
                calculateDistance(location);
            }
        }
    }

    @Override
    public void showMapModelList() {
        String[] strings = new String[]{"标准地图", "卫星地图", "夜间模式", "导航模式"};
        final NormalListDialog normalListDialog = new NormalListDialog(getActivity(), strings);
        normalListDialog.title("选择地图模式");
        normalListDialog.layoutAnimation(null);
        normalListDialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                        break;
                    case 1:
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                        break;
                    case 2:
                        aMap.setMapType(AMap.MAP_TYPE_NIGHT);//夜景地图模式
                        break;
                    case 3:
                        aMap.setMapType(AMap.MAP_TYPE_NAVI);//导航地图模式
                        break;
                }
                normalListDialog.dismiss();
            }
        });
        normalListDialog.show();
    }

    /**
     * description:计算当前偏移量
     */

    private void calculateDistance(final Location location) {
        if (calculateDistanceDisposable != null && !calculateDistanceDisposable.isDisposed()) {
            calculateDistanceDisposable.dispose();
        }
        Observable.create(new ObservableOnSubscribe<Float>() {
            private float distance = Float.MAX_VALUE;

            @Override
            public void subscribe(ObservableEmitter<Float> observableEmitter) throws Exception {
                for (CoordinateBean coordinateBean : copyCoordinateList) {
                    float distance0 = LocationManager.getDistance(location.getLatitude(), location.getLongitude(),
                            coordinateBean.getLatDouble(), coordinateBean.getLngDouble());
                    if (distance > distance0) {
                        distance = distance0;
                    }
                }
                observableEmitter.onNext(distance);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Float>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        calculateDistanceDisposable = d;
                    }

                    @Override
                    public void onNext(Float aFloat) {
                        deviate.setText(aFloat.intValue() + "/" + cruiseData.getThreshold() + "(米)");
                        //只有任务正在进行的时候才会弹出提醒
                        if (CruiseContract.TASK_IS_RUNNING.equals(cruiseData.getStatusInApp())) {
                            if (aFloat > Integer.valueOf(cruiseData.getThreshold())) {
                                showThresholdDialog();
                            } else {
                                closeThresholdDialog();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private NormalDialog thresholdDialog;//显示偏离路线对话框
    private long lastShowDialogTime;     //记录最近一次显示对话框的时间 十秒内不重复显示

    private void showThresholdDialog() {
        if (thresholdDialog == null) {
            thresholdDialog = new NormalDialog(getActivity());
            thresholdDialog.btnText("确定");
            thresholdDialog.content("已经偏离路线");
        }
        if (!thresholdDialog.isShowing() && TimeUtils.currentTime() - lastShowDialogTime > 10 * 1000) {
            thresholdDialog.show();
            lastShowDialogTime = TimeUtils.currentTime();
        }
    }

    private void closeThresholdDialog() {
        if (thresholdDialog != null && thresholdDialog.isShowing()) {
            thresholdDialog.dismiss();
        }
    }
}
